package com.ctrip.ec.api.mobile.controller;

import com.ctrip.ec.api.mobile.common.PagerInfo;
import com.ctrip.ec.api.mobile.common.RequestContext;
import com.ctrip.ec.api.mobile.common.ValidateException;
import com.ctrip.ec.api.mobile.model.GoodsModel;
import com.ctrip.ec.biz.dao.activity.ActivityDao;
import com.ctrip.ec.biz.dao.activity.ActivityShareDao;
import com.ctrip.ec.biz.dao.brand.BrandDao;
import com.ctrip.ec.biz.dao.forward.ForwardGoodsDao;
import com.ctrip.ec.biz.dao.goods.GoodsImageDao;
import com.ctrip.ec.biz.dao.goods.GoodsRebateDao;
import com.ctrip.ec.biz.dao.goods.GoodsSpecDao;
import com.ctrip.ec.biz.entity.activity.ActivityEntity;
import com.ctrip.ec.biz.entity.activity.ActivityShareEntity;
import com.ctrip.ec.biz.entity.brand.BrandEntity;
import com.ctrip.ec.biz.entity.forward.ForwardGoodsEntity;
import com.ctrip.ec.biz.entity.goods.*;
import com.ctrip.ec.biz.dao.goods.GoodsDao;
import com.ctrip.ec.dal.EntityBase;
import com.ctrip.ec.dal.PagerSetting;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsDao goods;

    @Autowired
    private ActivityDao activity;

    @Autowired
    private GoodsImageDao goodsImage;

    @Autowired
    private GoodsSpecDao goodsSpec;

    @Autowired
    private ActivityShareDao activityShare;

    @Value("${imageDomain}")
    private String imageDomain;

    @Autowired
    private BrandDao brand;

    @Autowired
    private ForwardGoodsDao forwardGoods;


    @GetMapping("list")
    public List<GoodsModel> list(@RequestParam(required = false) Long activityId,
                                 @RequestParam(required = false) Long brandId,
                                 @RequestParam(required = false) Long shareId,
                                 @RequestParam(required = false) Integer pageIndex,
                                 @RequestParam(required = false) Integer pageSize) throws SQLException {

        if (brandId == null) {
            ActivityEntity activityEntity = activity.entity(activityId);
            if (activityEntity == null) {
                throw new ValidateException("该活动已下架");
            }
            brandId = activityEntity.getBrandId();
        } else { //如果直接传的品牌过来，需要把活动找到
            ActivityEntity activityEntity = activity.latestByBrandId(brandId);
            activityId = activityEntity.getId();
        }

        BrandEntity brandEntity = brand.entity(brandId);


        String where = "is_on_sale=1 and brand_id= " + brandId;
        PagerSetting setting = new PagerSetting();

        setting.setWhere(where);

        long agentId = RequestContext.getAgentId();
        List<ForwardGoodsEntity> forwardGoodsList = null;
        if (agentId == 0) {
            setting.appendWhere("agent_id=0");
        } else { //小程序的商品是转发过来的基自己上传的，转发过来的需要加价
            setting.appendWhere("(agent_id=" + agentId + " or id in (select goods_id from " + EntityBase.getTableName(ForwardGoodsEntity.class)
                    + " where activity_id = " + activityId + " and agent_id=" + agentId + "))");
            forwardGoodsList = forwardGoods.list(" activity_id = " + activityId + " and agent_id=" + agentId);
        }
        setting.setOrderBy("cat_sort desc,cat_id desc,id desc");
        if (pageIndex != null) {
            setting.setPageIndex(pageIndex);
        }
        if (pageSize != null) {
            setting.setPageSize(pageSize);
        }

        List<GoodsEntity> list = goods.list(setting);
        List<GoodsModel> models = new ArrayList<>();
        ActivityShareEntity activityShareEntity = null;

        if (shareId != null) {
            activityShareEntity = activityShare.entity(shareId);
        }

        for (GoodsEntity entity : list) {
            GoodsModel model = new GoodsModel(entity);
            model.setImageList(goodsImage.listByGoodsId(entity.getId()));
            for (GoodsImageEntity imageEntity : model.getImageList()) {
                imageEntity.setImageUrl(this.imageDomain + imageEntity.getImageUrl());
            }

            //这里需要取品牌logo
            model.setOriginalImg(this.imageDomain + brandEntity.getLogoImageUrl());
            model.setSpecList(goodsSpec.listByGoodsId(entity.getId()));
            if (activityShareEntity != null) {//整场转发

                BigDecimal oldPrice = null;
                BigDecimal newPrice= null;
                for (GoodsSpecEntity specEntity : model.getSpecList()) {
                    if(oldPrice == null){
                        oldPrice = specEntity.getShopPrice().add(specEntity.getAgencyPrice());
                        newPrice = specEntity.getShopPrice().add(specEntity.getAgencyPrice()).add(activityShareEntity.getAddPrice());
                    }
                    specEntity.setShopPrice(specEntity.getShopPrice().add(specEntity.getAgencyPrice()).add(activityShareEntity.getAddPrice()));
                }

                //处理一下文案里的价格
                String strOldPrice = oldPrice.setScale(2,BigDecimal.ROUND_HALF_UP).toString();
                String strNewPrice = newPrice.setScale(2,BigDecimal.ROUND_HALF_UP).toString();
                model.setName(model.getName().replace(strOldPrice, strNewPrice));

            }

            //解决小程序加价问题
            if(agentId>0){
                Optional<ForwardGoodsEntity> forwardGoodsEntityOptional = forwardGoodsList.stream().filter(t->t.getGoodsId().equals(entity.getId())).findFirst();
                if(forwardGoodsEntityOptional.isPresent()){
                    for(GoodsSpecEntity specEntity: model.getSpecList()){
                        specEntity.setShopPrice(specEntity.getShopPrice().add(forwardGoodsEntityOptional.get().getAddPrice())); //这里没有加上代购价
                    }
                }


            }

            models.add(model);
        }
        RequestContext.setResponseHeaderPager(new PagerInfo(setting.getRecordCount(), pageIndex, pageSize));
        return models;
    }

    @GetMapping("search")
    public List<GoodsModel> search(@RequestParam(required = false) String condition,
                                   @RequestParam(required = false) Integer pageIndex,
                                   @RequestParam(required = false) Long brandId,
                                   @RequestParam(required = false) Integer pageSize) throws SQLException {

        if (Strings.isNullOrEmpty(condition)) {
            throw new ValidateException("搜索条件不能为空");
        }

        //小程序里的搜索也已经解决
        String where = "is_on_sale=1 and name like ? " +
                " and brand_id in (select brand_id from " + EntityBase.getTableName(ActivityEntity.class) + " where end_time >=? and ( agent_id=" + RequestContext.getAgentId() +
                " or id in ( select activity_id from " + EntityBase.getTableName(ForwardGoodsEntity.class) + " where agent_id=" + RequestContext.getAgentId() + ")))";


        if (brandId != null) {
            where += " and brand_id=" + brandId;
        }

        PagerSetting setting = new PagerSetting();
        setting.setWhere(where);

        setting.setOrderBy("cat_sort desc,cat_id desc,id desc");


        if (pageIndex != null) {
            setting.setPageIndex(pageIndex);
        }
        if (pageSize != null) {
            setting.setPageSize(pageSize);
        }

        Timestamp now = new Timestamp(System.currentTimeMillis());
        List<GoodsEntity> list = goods.list(setting, "%" + condition + "%", now);
        // List<ActivityEntity> activityList = activity.listByIds(list.stream().map(t->t.geta));

        //找到所有活动中的品牌
        List<Long> inActivityBrandList = brand.list("id in  (select brand_id from " + EntityBase.getTableName(ActivityEntity.class) + " where end_time >=? and begin_time<=?)", now, now)
                .stream().map(t -> t.getId()).collect(Collectors.toList());

        List<GoodsModel> models = new ArrayList<>();
        for (GoodsEntity entity : list) {
            GoodsModel model = new GoodsModel(entity);
            if (inActivityBrandList.contains(model.getBrandId())) {
                model.setCanBuy(true);
            } else {
                model.setCanBuy(false);
            }
            model.setImageList(goodsImage.listByGoodsId(entity.getId()));
            for (GoodsImageEntity imageEntity : model.getImageList()) {
                imageEntity.setImageUrl(this.imageDomain + imageEntity.getImageUrl());
            }
            model.setOriginalImg(this.imageDomain + model.getOriginalImg());
            model.setSpecList(goodsSpec.listByGoodsId(entity.getId()));

            models.add(model);
        }

        RequestContext.setResponseHeaderPager(new PagerInfo(setting.getRecordCount(), pageIndex, pageSize));

        return models;
    }


    @GetMapping("detail/{id}")
    public GoodsModel detail(@PathVariable Long id) throws SQLException {

        GoodsEntity entity = goods.entity(id);

        GoodsModel model = new GoodsModel(entity);


        model.setImageList(goodsImage.listByGoodsId(id));


        model.setSpecList(goodsSpec.listByGoodsId(id));
        return model;
    }
}